#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import urllib, urllib2
import base64

friendsTimelineUrl = 'http://api.fanfou.com/statuses/friends_timeline.xml'
updateUrl = 'http://api.fanfou.com/statuses/update.xml'
userTimelineUrl = 'http://api.fanfou.com/statuses/user_timeline.xml'
publicTimelineUrl = 'http://api.fanfou.com/statuses/public_timeline.xml'

class fanfou:
	
	def __init__(self, name, password):
		base64str = base64.b64encode(name + ':' + password)
		self.Auth_str = 'Basic '+base64str
		print 'init'
		
	def get_timeline(self, fetch_url, params = {}):
		req = urllib2.Request(fetch_url + '?' + urllib.urlencode(params))
		req.add_header('Authorization', self.Auth_str)
		try:
			handle = urllib2.urlopen(req)
			return handle.read()
		except IOError, e:
			print 'error'
			return 'error'
			
	def post_msg(self, url, msg, params = {}):
		params['status'] = msg
		req = urllib2.Request(url, urllib.urlencode(params))
		req.add_header('Authorization', self.Auth_str)
		try:
			handle = urllib2.urlopen(req)
			return handle.read()
		except IOError, e:
			print 'error'
			return 'error'
			
	def get_friends_timeline(self, count = 20):
		params = {}
		params['count'] = str(count)
		return self.get_timeline(friendsTimelineUrl, params)
		
	def get_pubilc_timeline(self, count = 20):
		params = {}
		params['count'] = str(count)
		return self.get_timeline(publicTimelineUrl, params)
		
	def update(self, msg):
		self.post_msg(updateUrl, msg)
